/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dbsucxentW.storageW.parserW;

/**
 * An object in charge of calculating the SiblingOrder of each leaf node in the
 * data source given that the leaves are passed in the document order
 * @author truongbaquan
 */
public class SiblingSumCalculator {
    private DocumentSummary summary;
    private String[] elementNames;
    private long[] sum;
    private SiblingCount siblingOrder;

    public SiblingSumCalculator(DocumentSummary summary, String[] elementNames) {
        this.summary = summary;
        this.elementNames = elementNames;
        this.sum = new long[summary.getMaxDepth() + 1];
        for (int i = 0; i < sum.length; i++) {
            sum[i] = 0;
        }
        this.siblingOrder = new SiblingCount();
    }

    public long calculate(int branchOrder, int depth) {
        if (branchOrder > 0) {
            siblingOrder.setLevel(branchOrder);				//klarinda 20060628
            int sOrd = siblingOrder.add(elementNames[branchOrder + 1]);
            long siblingSum = sum[branchOrder - 1] + sOrd * summary.getRValue(branchOrder);

            for (int x = branchOrder; x <= summary.getMaxDepth(); x++) {
                sum[x] = siblingSum;
            }
            for (int x = branchOrder + 1; x < depth; x++) {
                siblingOrder.setLevel(x);
                siblingOrder.add(elementNames[x + 1]);
            }
            return siblingSum;
        }
        else {
            for (int i = 0; i < depth; i++) {
                siblingOrder.setLevel(i);
                siblingOrder.add(elementNames[i + 1]);
            }
            return 0;
        }
    }
}
